import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { StorageService } from './storage.service';
import { HttpService } from './http.service';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivate {
  constructor(private storage:StorageService,private router:Router,private http:HttpService){}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    // 获取用户信息
    return new Promise((resolve,reject)=>{
      // 1、获取用户信息
      let userinfo=this.storage.get("userinfo");    
      if(!userinfo || !userinfo.username){     
        this.router.navigate(["/login"])
      }else{
        //2、请求接口验证token
        var api = "/api/validateToken";
        this.http.get(api, {
          auth: {
            username: userinfo.token,
            password: ''
          }
        }).then((response: any) => {             
          if (response.data.success == false && response.data.message=="token_error") {
            //验证token有没有过期
            this.router.navigate(["/login"])
          }else{
            resolve(true);
          }
        })
      }
  })
}
}
